﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UFPE.CIn.Abc.Primality.Util;
using System.Diagnostics;

namespace UFPE.CIn.Abc.Primality.Algorithms
{
    public class SieveOfEratosthenes
    {
        private static SieveOfEratosthenes instance;

        public static SieveOfEratosthenes Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = new SieveOfEratosthenes();
                }

                return instance;
            }
        }

        private bool[] numberArray;

        private int greatest;

        public int Greatest
        {
            get { return greatest; }
            set { greatest = value; }
        }

        public bool SievedIsPrime(int i)
        {
            if (i < numberArray.Length)
            {
                return !numberArray[i];
            }
            else
            {
                throw new Exception("Last sieve didn't passed through " + i);
            }
        }

        public bool IsPrime(BigInteger x, System.IO.TextWriter tw)
        {
            Stopwatch cron = Stopwatch.StartNew();

            int xInt = int.MaxValue;

            if (x < int.MaxValue)
            {
                xInt = x.IntValue();
            }
            
            numberArray = new bool[xInt + 1];
            //int i, j;
            for (int i = 2; i <= x; i++)
            {
                if (!numberArray[i])
                {
                    if (tw != null)
                    {
                        tw.Write(i + ", ");
                    }
                    greatest = i;

                    for (int j = i + i; j <= x; j += i)
                    {
                        numberArray[j] = true;
                    }
                }

            }

            if (tw != null)
            {
                tw.WriteLine();
            }

            cron.Stop();
            timeLastRun = cron.ElapsedMilliseconds;
            return !numberArray[xInt];
        }

        public bool IsProbablyPrime(BigInteger x, int prob)
        {
            return IsPrime(x, null);
        }

        private long timeLastRun;

        public long TimeLastRun
        {
            get { return timeLastRun; }
        }
    }
}
